package com.ltmall.api.controller;

import com.ltmall.api.bean.*;
import com.ltmall.api.entity.JsonCart;
import com.ltmall.api.entity.JsonShop;
import com.ltmall.api.entity.info.MemberDeductibleInfo;
import com.ltmall.api.manager.*;
import com.ltmall.api.parse.CartParse;
import com.ltmall.api.util.RemoteUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.*;

@Controller
public class CartController {

    boolean opTag, valiTag;

    private CartManager cartManager;
    private AccountManager accountManager;
    private GoodsManager goodsManager;
    private MembershipManager membershipManager;
    private DirectSupplyGoodsManager directSupplyGoodsManager;

    // 商品添加购物车
    public void cartAdd(HttpServletRequest request, HttpServletResponse response) {
        Cart cart = (Cart) RemoteUtil.request(request, new Cart());
        String userToken = request.getParameter("userToken");
        valiTag = accountManager.validate(cart.getUserID(), userToken);

        // 提交之前获取一下商品的商家  购物车表和商品表里面的goods ID不一样吗？
        Goods goods = goodsManager.goodsDetail(cart.getGoodsID());
        if (goods == null) {
            RemoteUtil.response(response, null, -2, "商品不存在");
            return;
        }

        // 添加商店ID
        cart.setShopID(goods.getShopID());
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }

        int oldNumber = 0;
        // 先判断存在相同规格的商品
        Cart oldCart = cartManager.isGoodsExist(cart.getGoodsID(), cart.getUserID(), cart.getGoodsFormat());
        if (oldCart != null) {
            oldNumber = oldCart.getNumber();
        }

        // if(goods.getGoodsNumber()<(cart.getNumber()+oldNumber)){//商品数量小于购物车的数量
        // RemoteUtil.response(response, null, -3, "商品库存不足");
        // return;
        // }

        int numberLimit = checkNumberLimit(goods.getGoodsID(), cart.getGoodsFormat(),
                cart.getNumber() + oldNumber, cart.getSkuID());
        if (numberLimit != 1) {
            String context = null;
            switch (numberLimit) {
                case -3:
                    context = "商品库存不足";
                    break;
                case -4:
                    context = "活动库存不足";
                    break;
                case -5:
                    ActivityPrice ap = cartManager.getActivityPrice(goods.getGoodsID(),
                            cart.getGoodsFormat());
                    int limitNumber = ap.getLimit();
                    context = "商品限购" + limitNumber + "件，加入购物车失败";
                    break;
            }
            RemoteUtil.response(response, null, numberLimit, context);
            return;
        }
        //存在修改数量
        if (oldCart != null) {
            int number = cart.getNumber() + oldCart.getNumber();
            String goodsFlavor = oldCart.getGoodsFlavor() + ";" + cart.getGoodsFlavor() + ","
                    + cart.getNumber();
            opTag = cartManager.updateCart(oldCart.getCartID(), number, goodsFlavor);
        } else {
            cart.setGoodsFlavor(cart.getGoodsFlavor() + "," + cart.getNumber());
            opTag = cartManager.addCart(cart);
        }

        if (opTag) {
            RemoteUtil.response(response, null, 1, "操作成功");
        } else {
            RemoteUtil.response(response, null, -1, "操作失败");
        }
    }

    public int checkNumberLimit(int goodsID, String goodsFormat, int buyNumber, int skuID) {
        /*
         * -3:商品库存不足； -4:活动商品库存不足； -5:超过限购数量；
         */

        int tag = 1;
        /*
         * ：判断该商品是否是活动商品 是：判断超过活动商品库存 判断超过个人限购 不是：判断是否超过商品库存
         */

        ActivityPrice ap = cartManager.getActivityPrice(goodsID, goodsFormat);
        if (ap != null) {
            // 大于活动库存
            if ((ap.getNumber() - ap.getSellOut()) < buyNumber) {
                tag = -4;
            }
            // 大于个人限购
            else if (ap.getLimit() < buyNumber) {
                tag = -5;
            }
        } else {
            ThSku sku = goodsManager.skuGet(skuID);
            // 大于商品库存
            if (sku.getStock() < buyNumber) {
                tag = -3;
            }
        }
        return tag;
    }

    // 修改购物车数量
    public void editNumber(HttpServletRequest request, HttpServletResponse response) {
        Cart cart = (Cart) RemoteUtil.request(request, new Cart());
        String userToken = request.getParameter("userToken");
        valiTag = accountManager.validate(cart.getUserID(), userToken);
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }

        Cart cart1 = cartManager.cartDetail(cart.getCartID());
        Goods goods = goodsManager.goodsDetail(cart1.getGoodsID());

        if (goods == null) {
            RemoteUtil.response(response, null, -2, "商品不存在");
            return;
        }

        /*
         * 如果数量是减少的，允许修改如果是增加就判断
         */
        if (cart.getNumber() > cart1.getNumber()) {
            int numberLimit = checkNumberLimit(goods.getGoodsID(), cart1.getGoodsFormat(),
                    cart.getNumber(), cart1.getSkuID());
            if (numberLimit != 1) {
                String context = null;
                switch (numberLimit) {
                    case -3:
                        context = "商品库存不足";
                        break;
                    case -4:
                        context = "活动库存不足";
                        break;
                    case -5:
                        ActivityPrice ap = cartManager.getActivityPrice(goods.getGoodsID(),
                                cart.getGoodsFormat());
                        int limitNumber = ap.getLimit();

                        context = "商品限购" + limitNumber + "件，加入购物车失败";
                        // context = "超过活动限购";
                        break;
                }
                RemoteUtil.response(response, null, numberLimit, context);
                return;
            }
        }

        opTag = cartManager.updateNumber(cart.getNumber(), cart.getCartID());
        if (opTag) {
            RemoteUtil.response(response, null, 1, "操作成功");
        } else {
            RemoteUtil.response(response, null, -1, "操作失败");
        }
    }

    // 删除购物车
    public void delCart(HttpServletRequest request, HttpServletResponse response) {
        Cart cart = (Cart) RemoteUtil.request(request, new Cart());
        String userToken = request.getParameter("userToken");
        valiTag = accountManager.validate(cart.getUserID(), userToken);
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }
        opTag = cartManager.delCart(cart.getCartID());
        if (opTag) {
            RemoteUtil.response(response, null, 1, "操作成功");
        } else {
            RemoteUtil.response(response, null, -1, "操作失败");
        }
    }

    /**
     * 获取购物车
     *
     * @param
     */
    public void cartList(HttpServletRequest request, HttpServletResponse response) {
        Cart cart = (Cart) RemoteUtil.request(request, new Cart());
        String userToken = request.getParameter("userToken");
        valiTag = accountManager.validate(cart.getUserID(), userToken);
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }
        List<?> shopList = cartManager.shopList(cart.getUserID());
        List<JsonShop> returnList = CartParse.shopParse(shopList, cart.getUserID(), cartManager,
                goodsManager, false);
        RemoteUtil.response(response, returnList, 1, "返回成功");
    }

    /**
     * 获取购物车列表接口
     *
     * @param request
     * @param response
     * @author x1ny
     */
    public void listsGet(HttpServletRequest request, HttpServletResponse response) {
        Map<String, JsonShop> jsonShopMap = new HashMap<>();
        try {

            int userID = Integer.parseInt(request.getParameter("userID"));
            int directID = 0;
            if (StringUtils.isNotEmpty(request.getParameter("directID"))) {
                directID = Integer.parseInt(request.getParameter("directID"));
            }

            MemberDeductibleInfo info = membershipManager.getDeductible(userID);
            List<?> jsonShopAndGoods = cartManager.shopAndgoodsList(userID, directID);
            for (int i = 0; i < jsonShopAndGoods.size(); i++) {
                Object[] obj = (Object[]) jsonShopAndGoods.get(i);
                JsonShop jsonShop = null;
                if (jsonShopMap.containsKey(obj[0].toString())) {
                    jsonShop = jsonShopMap.get(obj[0].toString());
                } else {
                    jsonShop = new JsonShop();
                    jsonShop.setShopID(Integer.parseInt(obj[0].toString()));
                    jsonShop.setShopName(obj[1].toString());
                    jsonShop.setCartList(new LinkedList<JsonCart>());
                    jsonShopMap.put(obj[0].toString(), jsonShop);
                }
                JsonCart jsonCart = new JsonCart();
                jsonCart.setCartID(Integer.parseInt(obj[2].toString()));
                jsonCart.setGoodsID(Integer.parseInt(obj[3].toString()));
                jsonCart.setGoodsName(obj[4].toString());
                //这里的价格问题
                String activityName = obj[10].toString();
                //社区团购
                if ("ThGroupBuyingRules".equals(activityName)) {
                    double price = 0;
                    //查询购物车详情
                    Cart cart = cartManager.cartDetail(Integer.parseInt(obj[2].toString()));
                    //查询sku
                    ThSku sku = goodsManager.skuGet(cart.getSkuID());
                    //查询团购基本信息
                    ThGroupBuyingRules rule = goodsManager.groupBuyingRuleGet(cart
                            .getGroupRulesID());

                    //团购活动是否过期
                    String isOverdue = (new Date()).after(rule.getEndingAt()) ? "TRUE" : "FALSE";
                    jsonCart.setIsOverdue(isOverdue);

                    //团购限购数量
                    // jsonCart.setGoodsLimitBuy(rule.getGoodsLimitBuy());
                    //限购数量变更成用户目前可购买该团购商品的数量（限购数量-已购买数量）
                    int buyingAmount = directSupplyGoodsManager.getUserGroupBuyingAmount(
                            cart.getGroupRulesID(), userID);
                    int leftAmount = rule.getGoodsLimitBuy() - buyingAmount;
                    jsonCart.setGoodsLimitBuy(leftAmount);

                    //判断是否为阶梯费用
                    if (rule.getIsLadderPrice() == 0) {
                        //不执行阶梯价格
                        price = sku.getPrice();
                    } else {
                        //执行阶梯价格
                        int groupJoinPeople = 0; //参团人数
                        ThGroupBuying group = goodsManager.groupBuyingGetByRulesId(rule.getId());
                        //首次开团
                        if (group != null) {
                            groupJoinPeople = group.getGroupJoinPeople();
                        }

                        //判断当前团购人数属于哪个区间
                        if (groupJoinPeople < rule.getLevel2Num()) {
                            price = Double.parseDouble(sku.getLevel1Price());
                        } else if (groupJoinPeople >= rule.getLevel2Num()
                                && groupJoinPeople < rule.getLevel3Num()) {
                            price = Double.parseDouble(sku.getLevel2Price());
                        } else if (groupJoinPeople >= rule.getLevel3Num()) {
                            price = Double.parseDouble(sku.getLevel3Price());
                        }
                    }

                    jsonCart.setGoodsPrice(price);
                    jsonCart.setGroupType(rule.getGroupType());
                } else {
                    jsonCart.setGoodsPrice(Double.parseDouble(obj[11].toString()));
                }

                jsonCart.setGoodsPicture(CartParse.getGoodsPicPath(obj[5].toString()));
                jsonCart.setGoodsType(Integer.parseInt(obj[6].toString()));
                jsonCart.setGoodsNumber(Integer.parseInt(obj[7].toString()));
                jsonCart.setGoodsFormat(obj[8].toString());
                jsonCart.setActivityID(Integer.parseInt(obj[9].toString()));
                jsonCart.setActivityName(activityName);
                jsonCart.setOldPrice(Integer.parseInt(obj[12].toString()));
                jsonCart.setStock(Integer.parseInt(obj[13].toString()));
                jsonCart.setFormatHidden(Integer.parseInt(obj[14].toString()));
                jsonCart.setGoodsShow(Integer.parseInt(obj[15].toString()));
                jsonCart.setGoodsStation(Integer.parseInt(obj[16].toString()));
                jsonCart.setDirectId(Integer.parseInt(obj[18].toString()));
                jsonCart.setGoodsShotName(obj[19].toString());
                //董事特权可抵扣金额
                jsonCart
                        .setPrivateProfitShare((Double.parseDouble(obj[17].toString()) / 100.0) * 0.9);
                //实际抵扣金额
                jsonCart.setProfitShare((Double.parseDouble(obj[17].toString()) / 100.0)
                        * (info.getDeductible()));

                jsonShop.getCartList().add(jsonCart);
            }
            RemoteUtil.response(response, jsonShopMap.values(), 1, "返回成功");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            RemoteUtil.response(response, jsonShopMap.values(), 0, "操作失败");
        }
    }

    public void showCartCount(HttpServletRequest request, HttpServletResponse response) {
        Cart cart = (Cart) RemoteUtil.request(request, new Cart());
        int cartListCount = cartManager.cartListCount(cart.getUserID());
        System.out.println("cartListCount:  " + cartListCount);
        RemoteUtil.response(response, cartListCount, 1, "返回成功");

    }

    //普通商品加入购物车
    public void listAdd(HttpServletRequest request, HttpServletResponse response) {
        Cart list = (Cart) RemoteUtil.request(request, new Cart());

        String context;

        String userToken = request.getParameter("userToken");
        validate(list.getUserID(), userToken, response);

        // 看下这个商品到底存不存在
        Goods goods = goodsManager.goodsDetail(list.getGoodsID());
        if (goods == null) {
            RemoteUtil.response(response, null, -2, "商品不存在");
            return;
        }

        // 商品SKU新购买的数量
        int numberNewInList = 0;
        numberNewInList = list.getNumber();

        // 添加商店ID
        list.setShopID(goods.getShopID());

        // 商品SKU已经购买数量
        int numberHaveInList = 0;
        Cart oldList = null;
        if ("ThGroupBuyingRules".equals(list.getActivityName())) {
            //团购商品
            oldList = cartManager.isGroupGoodsExist(list.getGoodsID(), list.getUserID(),
                    list.getGoodsFormat(), list.getDirectID());
        } else {
            //普通商品
            // 先判断购物清单中是否存在存在相同规格的商品
            oldList = cartManager.isGoodsExist(list.getGoodsID(), list.getUserID(),
                    list.getGoodsFormat());
        }

        if (oldList != null) {
            numberHaveInList = oldList.getNumber();
        }

        int number = numberNewInList + numberHaveInList;

        //检查库存
        int flag = checkNumberLimit(list.getGoodsID(), number, list.getSkuID());
        if (flag != 1) {
            context = "商品库存不足";
            switch (flag) {
                case -3:
                    context = "商品库存不足";
                    break;
                case -9:
                    context = "不支持购买";
                    break;
                default:
                    break;
            }
            RemoteUtil.response(response, null, flag, context);
            return;
        }

        if (oldList != null) {// 存在修改数量
            String goodsFlavor = oldList.getGoodsFlavor() + ";" + list.getGoodsFlavor() + ","
                    + list.getNumber();
            opTag = cartManager.updateCart(oldList.getCartID(), number, goodsFlavor);
        } else {
            list.setGoodsFlavor(list.getGoodsFlavor() + "," + list.getNumber());
            opTag = cartManager.addCart(list);
        }

        if (opTag) {
            context = "加入购物车成功";
            RemoteUtil.response(response, null, 1, context);
            return;
        } else {
            context = "加入购物车失败";
            RemoteUtil.response(response, null, -1, context);
            return;
        }
    }

    //疯抢活动增加购物车
    public void panicActivityListAdd(HttpServletRequest request, HttpServletResponse response) {
        Cart list = (Cart) RemoteUtil.request(request, new Cart());
        /*
         * -3:商品库存不足； -4:活动商品库存不足； -5:超过限购数量； -6:活动尚未开始
         */
        String context = "";

        String userToken = request.getParameter("userToken");
        validate(list.getUserID(), userToken, response);

        //TODO 判断活动是否还生效

        // 看下这个商品到底存不存在
        Goods goods = goodsManager.goodsDetail(list.getGoodsID());
        if (goods == null) {
            RemoteUtil.response(response, null, -2, "商品不存在");
            return;
        }

        // 商品SKU新购买的数量
        int numberNewInList = 0;
        numberNewInList = list.getNumber();

        // 添加商店ID
        list.setShopID(goods.getShopID());

        // 商品SKU购买数量
        int numberInList = 0;

        // 先判断已有的购物清单中是否存在存在相同规格的商品，并且处于活动中
        Cart oldList = cartManager.isGoodsExist(list.getGoodsID(), list.getUserID(),
                list.getSkuID(), list.getActivityID(), list.getActivityName());
        if (oldList != null) {
            numberInList = oldList.getNumber();
        }

        int number = numberNewInList + numberInList;
        int flag = checkActivityNumberLimit(list, number);
        switch (flag) {
            case -4:
                context = "活动库存不足";
                RemoteUtil.response(response, null, -4, context);
                return;
            case -5:
                if (oldList != null) {
                    ActivityPrice actSku = goodsManager.getActivityPrice(oldList.getGoodsID(),
                            oldList.getGoodsFormat());
                    context = "商品限购" + actSku.getLimit() + "件，加入购物车失败";
                    RemoteUtil.response(response, null, -5, context);
                } else {
                    ActivityPrice actSku = goodsManager.getActivityPrice(list.getGoodsID(),
                            list.getGoodsFormat());
                    context = "商品限购" + actSku.getLimit() + "件，加入购物车失败";
                    RemoteUtil.response(response, null, -5, context);
                }
                return;
            case -6:
                context = "活动尚未开始";
                RemoteUtil.response(response, null, -6, context);
                return;
        }

        // 存在修改数量
        if (oldList != null) {
            String goodsFlavor = oldList.getGoodsFlavor() + ";" + list.getGoodsFlavor() + "," + list.getNumber();
            opTag = cartManager.updateCart(oldList.getCartID(), number, goodsFlavor);
        } else {
            list.setGoodsFlavor(list.getGoodsFlavor() + "," + list.getNumber());
            opTag = cartManager.addCart(list);
        }

        if (opTag) {
            RemoteUtil.response(response, null, 1, "操作成功");
        } else {
            RemoteUtil.response(response, null, -1, "操作失败");
        }
    }

    private int checkActivityNumberLimit(Cart list, int number) {
        /*
         * -4:活动商品库存不足； -5:超过限购数量； -6:活动尚未开始
         */
        List<?> oc = null;
        int orderNum = 0;

        ActivityPrice actSku = null;
        // 判断商品是否处于今日疯抢的活动中
        if (list.getActivityName().equals("ThPanicBuyingSku") && list.getActivityID() > 0) {
            //actSku = cartManager.panicSKuGet(list.getSkuID(),list.getActivityID());
            actSku = goodsManager.getActivityPrice(list.getGoodsID(), list.getGoodsFormat());
            if (actSku != null) {
                //根据SkuId从订单中查找该商品
                oc = cartManager.ordersGet(list.getSkuID(), list.getUserID(), "ThPanicBuyingSku",
                        actSku.getActivityID());
                for (int i = 0; i < oc.size(); i++) {
                    int ordersNumber = Integer.parseInt(oc.get(i).toString());
                    orderNum += ordersNumber;
                }
            } else {
                return -6;
            }
        }

        if (orderNum + number > actSku.getLimit()) {
            return -5;
        } else if (number > actSku.getNumber()) {
            return -4;
        }
        return 1;
    }

    //检查普通商品购买限制
    private int checkNumberLimit(int goodsID, int buyNumber, int skuID) {
        //检查库存是否还能够支持继续购买
        ThSku sku = goodsManager.skuGet(skuID);

        // 大于商品库存
        if (sku.getStock() < buyNumber) {
            return -3;
        }
        Goods goods = goodsManager.goodsDetail(goodsID);
        if (goods.getGoodsType() == 3) {
            PrePay prePay = goodsManager.getPrepay(goodsID);
            String endTime = prePay.getEndTime() + ":00";
            Timestamp ss = Timestamp.valueOf(endTime);
            long endTimeLong = ss.getTime();
            long now = System.currentTimeMillis();
            if (now > endTimeLong) {
                return -9;
            }
        }
        return 1;
    }

    //修改购物车商品数量
    public void listUpdate(HttpServletRequest request, HttpServletResponse response) {
        String context = "";

        Cart shippingList = (Cart) RemoteUtil.request(request, new Cart());
        String userToken = request.getParameter("userToken");
        validate(shippingList.getUserID(), userToken, response);
        Cart shoppingListDetail = cartManager.cartDetail(shippingList.getCartID());
        Goods goods = goodsManager.goodsDetail(shoppingListDetail.getGoodsID());

        if (goods == null) {
            RemoteUtil.response(response, null, -2, "商品不存在");
            return;
        }

        /*
         * 如果数量是减少的，允许修改如果是增加就判断
         */
        if (shippingList.getNumber() > shoppingListDetail.getNumber()) {
            if (shoppingListDetail.getActivityID() > 0) {
                int flag = checkActivityNumberLimit(shoppingListDetail, shippingList.getNumber());
                switch (flag) {
                    case -4:
                        context = "活动库存不足";
                        RemoteUtil.response(response, null, -4, context);
                        return;
                    case -5:
                        //ActivityPrice actSku = cartManager.panicSKuGet(shoppingListDetail.getSkuID(),shoppingListDetail.getActivityID());
                        ActivityPrice actSku = goodsManager.getActivityPrice(
                                shoppingListDetail.getGoodsID(), shoppingListDetail.getGoodsFormat());
                        context = "商品限购" + actSku.getLimit() + "件，加入购物车失败";
                        RemoteUtil.response(response, null, -5, context);
                        return;
                    case -6:
                        context = "活动尚未开始";
                        RemoteUtil.response(response, null, -6, context);
                        return;
                }
            } else {
                int flag = checkNumberLimit(shoppingListDetail.getGoodsID(),
                        shippingList.getNumber(), shoppingListDetail.getSkuID());
                if (flag != 1) {
                    context = "商品库存不足";
                    switch (flag) {
                        case -3:
                            context = "商品库存不足";
                            break;
                        case -9:
                            context = "不支持购买";
                            break;
                        default:
                            break;
                    }
                    RemoteUtil.response(response, null, flag, context);
                    return;
                }
            }
        }
        opTag = cartManager.updateNumber(shippingList.getNumber(), shippingList.getCartID());
        if (opTag) {
            RemoteUtil.response(response, null, 1, "操作成功");
        } else {
            RemoteUtil.response(response, null, -1, "操作失败");
        }
    }

    //验证用户身份
    private void validate(int userId, String userToken, HttpServletResponse response) {
        valiTag = accountManager.validate(userId, userToken);
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }
    }

    /**
     * @param membershipManager the membershipManager to set
     */
    public void setMembershipManager(MembershipManager membershipManager) {
        this.membershipManager = membershipManager;
    }

    public GoodsManager getGoodsManager() {
        return goodsManager;
    }

    public void setGoodsManager(GoodsManager goodsManager) {
        this.goodsManager = goodsManager;
    }

    public AccountManager getAccountManager() {
        return accountManager;
    }

    public void setAccountManager(AccountManager accountManager) {
        this.accountManager = accountManager;
    }

    public CartManager getCartManager() {
        return cartManager;
    }

    public void setCartManager(CartManager cartManager) {
        this.cartManager = cartManager;
    }

    /**
     * @param directSupplyGoodsManager the directSupplyGoodsManager to set
     */
    public void setDirectSupplyGoodsManager(DirectSupplyGoodsManager directSupplyGoodsManager) {
        this.directSupplyGoodsManager = directSupplyGoodsManager;
    }

}
